package visual;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import main.GameDef;
import main.GameMain;
import net.GameClient;
import net.Message;
import net.UserServer;

public class FrameHandler implements GameDef{
	public static Frame frame;

	public static Vector <String> piecesNames;
	public static Vector playerNames;
	
	public static void addFrame(Frame _frame){
		frame = _frame;
		piecesNames = new Vector<String>(STRING_PIECES.length);
		for(int i = 0; i < STRING_PIECES.length; i++){
			piecesNames.add(STRING_PIECES[i]);
		}
	}
	
	public static void handleActionEvent(ActionEvent event, Vector attributes) {
		if(event.getActionCommand().equals(MENU_GAME_STRINGS[MENU_GAME_STRING_NEWGAME])){
			createNewGameDialog();
		}else if(event.getActionCommand().equals(MENU_GAME_STRINGS[MENU_GAME_STRING_SAVEGAME])){
//			saveGame();
		}else if(event.getActionCommand().equals(MENU_GAME_STRINGS[MENU_GAME_STRING_LOADGAME])){
//			loadGame();
		}else if(event.getActionCommand().equals(MENU_GAME_STRINGS[MENU_GAME_STRING_EXITGAME])){
			frame.close();
		}else if(event.getActionCommand().equals(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_START])){
			frame.createGameBoard();
			if(attributes.get(2).equals(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_SERVER])){
				GameMain.client = new GameClient("localhost");
				GameMain.server = new UserServer(Integer.valueOf(attributes.get(3).toString()));
			} else {
				GameMain.client = new GameClient((String)attributes.get(0));
			}
			while(GameMain.client.oos == null){} //esperar hasta que el cliente se conecte y cree ouputStreams.
			GameMain.client.sendMessage(new Message(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_START], attributes, false));
		}else if(event.getActionCommand().equals(DIALOG_BUY_STRINGS[DIALOG_BUY_BUY])){
			showBuyDialog();
		}else if(event.getActionCommand().equals(DIALOG_BUY_STRINGS[DIALOG_BUY_PAY])){
			GameMain.client.sendMessage(new Message(DIALOG_BUY_STRINGS[DIALOG_BUY_PAY], attributes, false));
		}else if(event.getActionCommand().equals(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_ATTACK])){
			GameMain.client.sendMessage(new Message(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_ATTACK], attributes, false));
		}else if(event.getActionCommand().equals(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_ATTACK])){
			GameMain.client.sendMessage(new Message(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_ATTACK], attributes, false));
		}else if(event.getActionCommand().equals(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_FIRE])){
			playerCanAttack = true;
			GameMain.client.sendMessage(new Message("player to attack", attributes, false));
		}else if(event.getActionCommand().equals(FRAME_BUTTON_STRINGS[FRAME_BUTTON_REPAIR])){
			hasToRepair = true;
		}else if(event.getActionCommand().equals(FRAME_BUTTON_STRINGS[FRAME_BUTTON_ENDTURN])){
			GameMain.client.sendMessage(new Message(FRAME_BUTTON_STRINGS[FRAME_BUTTON_ENDTURN], null, false));
		}
	}
	
//	private static void loadGame() {
//		try{
//			FileInputStream fis = new FileInputStream("game.dat");
//			ObjectInputStream ois = new ObjectInputStream(fis);
//			GameMain.server.gameManager = (Manager)ois.readObject();
//		}catch(Exception e){
//			e.printStackTrace();
//			System.out.println("Couldn't load");
//		}
//	}
//
//	private static void saveGame() {
//		try{
//			FileOutputStream fos = new FileOutputStream("game.dat");
//			ObjectOutputStream oos = new ObjectOutputStream(fos);
//			oos.writeObject(GameMain.server.gameManager);
//		}catch(Exception e){
//			e.printStackTrace();
//			System.out.println("Couldn't save");
//		}
//		
//	}

	public static void createNewGameDialog(){
		Dialog newGameFrame = new Dialog(frame, DIALOG_NEWGAME_STRINGS[DIALOG_FRAME_NAME]){ //Clase anonima de InternalFrame
			JTextField ip = null;
			ButtonGroup group = new ButtonGroup();
			JTextField playerName = null;
			JTextField numberOfPlayers = null;
			
			public void actionPerformed(ActionEvent event) {
				if(event.getActionCommand().equals(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_CLIENT])){
					ip.setVisible(true);
					numberOfPlayers.setVisible(false);
				} else if(event.getActionCommand().equals(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_SERVER])){
					ip.setText(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_IP]);
					ip.setVisible(false);
					numberOfPlayers.setVisible(true);
				} else if(event.getActionCommand().equals(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_START])){
					attributes = new Vector(0);
					attributes.add(ip.getText());
					attributes.add(playerName.getText());
					attributes.add(group.getSelection().getActionCommand());
					attributes.add(numberOfPlayers.getText());
					savePlayerAttributes();
					dispose();
				}
				handleActionEvent(event, attributes);
			}
			
			public void savePlayerAttributes(){
				try{
					FileOutputStream fos = new FileOutputStream("player.dat");
					ObjectOutputStream oos = new ObjectOutputStream(fos);
					oos.writeObject(attributes);
				}catch(Exception e){
					e.printStackTrace();
					System.out.println("Couldn't save");
				}
			}
			
			public void loadPlayerAttributes(){
				try{
					FileInputStream fis = new FileInputStream("player.dat");
					ObjectInputStream ois = new ObjectInputStream(fis);
					attributes = (Vector)ois.readObject();
					playerName = new JTextField((String)attributes.get(1));
					ip = new JTextField((String)attributes.get(0));
				}catch(Exception e){
					System.out.println("Couldn't load");
					playerName = new JTextField(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_ENTERNAME]);
					ip = new JTextField(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_IP]);
				}
			}
			
			public void createDialog(){
				loadPlayerAttributes();
				
				playerName.setBorder(BorderFactory.createTitledBorder(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_PLAYER]));
				numberOfPlayers = new JTextField("2");
				numberOfPlayers.setBorder(BorderFactory.createTitledBorder("Jugadores"));
				getContentPane().setLayout(new FlowLayout());
				getContentPane().add(playerName);
				JRadioButton clientButton = new JRadioButton(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_CLIENT]);
				clientButton.setActionCommand(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_CLIENT]);
			    JRadioButton serverButton = new JRadioButton(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_SERVER]);
			    serverButton.setActionCommand(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_SERVER]);
			    group = new ButtonGroup();
			    group.add(clientButton);
			    group.add(serverButton);
			    clientButton.addActionListener(this);
			    serverButton.addActionListener(this);
		        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
		        radioPanel.add(clientButton);
		        radioPanel.add(serverButton);
		        getContentPane().add(radioPanel);
		        JPanel jtextPanel = new JPanel(new GridLayout(0, 1));
		        ip.setBorder(BorderFactory.createTitledBorder(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_CONNECTTO]));
		        jtextPanel.add(ip);
		        jtextPanel.add(numberOfPlayers);
		        getContentPane().add(jtextPanel);
		        JButton startGame = new JButton(DIALOG_NEWGAME_STRINGS[DIALOG_NEWGAME_START]);
				startGame.addActionListener(this);
				getContentPane().add(startGame);
			}
		};
	}
	
	public static void showBuyDialog(){
		Dialog buyDialog = new Dialog(frame, DIALOG_BUY_STRINGS[DIALOG_FRAME_NAME]){
			ButtonGroup group;
			
			public void actionPerformed(ActionEvent event){
				if(event.getActionCommand().equals(DIALOG_BUY_STRINGS[DIALOG_BUY_PAY])){
					attributes = new Vector(0);
					attributes.add(group.getSelection().getActionCommand());
					dispose();
				}
				handleActionEvent(event, attributes);
			}
			
			public void createDialog(){
				getContentPane().setLayout(new FlowLayout());
				JRadioButton []buyItemsRadio = new JRadioButton[STRING_PIECES.length];
				group = new ButtonGroup();
		        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
				for(int i = 0; i < buyItemsRadio.length; i++){
					buyItemsRadio[i] = new JRadioButton(STRING_PIECES[i]);
					buyItemsRadio[i].setActionCommand(STRING_PIECES[i]);
					group.add(buyItemsRadio[i]);
					buyItemsRadio[i].addActionListener(this);
					radioPanel.add(buyItemsRadio[i]);
				}
				JButton bBuy = new JButton(DIALOG_BUY_STRINGS[DIALOG_BUY_PAY]);
				bBuy.addActionListener(this);
				getContentPane().add(radioPanel);
				getContentPane().add(bBuy);
			}
		};
	}
	
	public static void showAttackDialog(){
		Dialog attackDialog = new Dialog(frame, DIALOG_ATTACK_STRINGS[DIALOG_FRAME_NAME]){
			ButtonGroup group;
			public void actionPerformed(ActionEvent event){
				if(event.getActionCommand().equals(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_FIRE])){
					attributes = new Vector(0);
					attributes.add(group.getSelection().getActionCommand());
					dispose();
				}
				handleActionEvent(event, attributes);
			}
			
			public void createDialog(){
				getContentPane().setLayout(new FlowLayout());
				JRadioButton []attackItemsRadio = new JRadioButton[playerNames.size()];
				group = new ButtonGroup();
		        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
				for(int i = 0; i < attackItemsRadio.length; i++){
					attackItemsRadio[i] = new JRadioButton((String) playerNames.get(i));
					attackItemsRadio[i].setActionCommand("i) " + (String) playerNames.get(i));
					group.add(attackItemsRadio[i]);
					attackItemsRadio[i].addActionListener(this);
					radioPanel.add(attackItemsRadio[i]);
				}
				JButton bAttack = new JButton(DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_FIRE]);
				bAttack.addActionListener(this);
		        getContentPane().add(radioPanel);
				getContentPane().add(bAttack);
			}
		};
	}

	public static boolean hasToPutPiece = false;
	public static boolean hasToPutCastle = true;
	public static boolean hasToPutPieceVertical = false;
	public static boolean playerCanAttack = false;
	public static boolean hasToRepair = false;
	public static int hasToPutPieceId = -1;

	public static void handleMessage(Message _msg){
		if(_msg.serverMsg){
			frame.gameInfoTextBox.append("\n- " + _msg.message);
		}else{
			if(_msg.message.equals("start game")){
				GameMain.client.clientId = (Integer)_msg.attributes.get(0);
			}else if(_msg.message.equals("piece paid")){
				hasToPutPiece = true;
				hasToPutPieceId = _msg.pieceType;
			}else if(_msg.message.equals("piece created")){
				hasToPutPiece = false;
				frame.boardCenter.castle.add(_msg.piece);
				frame.repaint();
			}else if(_msg.message.equals((DIALOG_ATTACK_STRINGS[DIALOG_ATTACK_ATTACK]))){
				playerNames = _msg.attributes;
				showAttackDialog();
			}else if(_msg.message.equals("No more attacks")){
				playerCanAttack = false;
			}else if(_msg.message.equals("INFO")){
				String text = "";
				text += _msg.attributes.get(0);
				for(int i = 0; i < PLAYER_INFO_STRINGS.length; i++){
					text += PLAYER_INFO_STRINGS[i] + _msg.attributes.get(i + 1);
				}
				frame.playerInfoTextBox.setText(text);
				if((Integer)_msg.attributes.get(INFO_CANT_ARMORY) > 0){
					frame.repairButton.setEnabled(true);
				} else {
					frame.repairButton.setEnabled(false);
				}
				if((Integer)_msg.attributes.get(INFO_CANT_ATTACKS) > 0){
					frame.attackButton.setEnabled(true);
				} else {
					frame.attackButton.setEnabled(false);
				}
			}
		}
	}
	
	
}